package com.ququ.syb.mqhandler.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ququ.common.result.ResultJson;
import com.ququ.syb.common.constant.PayChannelTypeConstant;
import com.ququ.syb.common.constant.PayOrderStatusConstant;
import com.ququ.syb.common.constant.RabbitMqQueueNameConstant;
import com.ququ.syb.common.constant.RedisKeyConstant;
import com.ququ.syb.common.pojo.PayChannel;
import com.ququ.syb.common.pojo.PayOrder;
import com.ququ.syb.mqhandler.fegin.ChannelsRouterFegin;
import com.ququ.syb.mqhandler.fegin.PayChannelFegin;
import com.ququ.syb.mqhandler.fegin.PayOrderFegin;
import com.ququ.syb.mqhandler.rabbitmq.RabbitMQSender;
import com.ququ.syb.mqhandler.redis.RedisDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

@Service
public class PayOrderQueryService {
    private Logger logger = LoggerFactory.getLogger(PayOrderQueryService.class);
    @Autowired
    private PayOrderFegin payOrderFegin;
    @Autowired
    private ChannelsRouterFegin channelsRouterFegin;
    @Autowired
    private PayChannelFegin payChannelFegin;
    @Autowired
    private RabbitMQSender rabbitMQSender;
    @Autowired
    private RedisDao redisDao;

    public void queryPayOrder(String tradenum) {
        Jedis jedis = redisDao.getJedis();
        try {
            PayOrder payOrder = payOrderFegin.getPayOrder(tradenum).getData();
            if (payOrder == null) {
                logger.error("生意宝无此订单:{}", tradenum);
                return;
            }
            if (payOrder.getStatus() == PayOrderStatusConstant.SUCCESS || payOrder.getStatus() == PayOrderStatusConstant.FAIL || payOrder.getStatus() == PayOrderStatusConstant.PAY_TO_ASSURE_SUCCESS) {
                logger.debug("{}订单已经成功或失败，无需查单", tradenum);
                return;
            }
            if (Integer.parseInt(jedis.get(RedisKeyConstant.PAYORDER_QUERY_TIMES+tradenum)) > 144){
                logger.debug("{}订单超过24小时未返回状态，停止查单处理",tradenum);
                return;
            }
            String paychannelid = payOrder.getPaychannelid();
            PayChannel payChannel = payChannelFegin.getPayChannel(paychannelid).getData();
            String extparams = null;
            if (paychannelid.length() == 3 && (paychannelid.startsWith("12") || paychannelid.startsWith("13"))) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("channelOrderNo", payOrder.getChannelpayno());
                extparams = jsonObject.toJSONString();
            }
            ResultJson resultJson = channelsRouterFegin.queryPay(payOrder.getPayeeaccount(), paychannelid, tradenum, extparams);
            String msg = tradenum + "支付订单状态:";
            if (resultJson.getStatus() == 1) {
                Map<String, Object> map = (Map<String, Object>) resultJson.getData();
                int status = Integer.parseInt(map.get("payStatus").toString());
                String errmsg = map.get("errorMsg").toString();
                switch (status) {
                    case 3:
                        msg = msg + "支付中。\n" + errmsg;
                        logger.debug("{}订单支付中，延时再次查单", tradenum);
                        String queue = (payChannel.getChanneltype() == PayChannelTypeConstant.SCAN)?RabbitMqQueueNameConstant.DEAD_PAYORDER_QUERY_5S:RabbitMqQueueNameConstant.DEAD_PAYORDER_QUERY_10MIN;
                        rabbitMQSender.send(queue, tradenum);
                        jedis.incr(RedisKeyConstant.PAYORDER_QUERY_TIMES+tradenum);
                        break;
                    case 4:
                        msg = msg + "支付成功。\n已自动补单";
                        if (payOrder.getStatus() == 3) {
                            Map<String, Object> map1 = new HashMap<>();
                            map1.put("tradenum", tradenum);
                            map1.put("status", 1);
                            rabbitMQSender.send(RabbitMqQueueNameConstant.PAYORDER_CALLBACK, JSON.toJSONString(map1));
                        }
                        break;
                    case 5:
                        msg = msg + "支付失败。\n原因是：" + errmsg + "\n已自动补单处理";
                        if (payOrder.getStatus() == 3) {
                            Map<String, Object> map2 = new HashMap<>();
                            map2.put("tradenum", tradenum);
                            map2.put("status", 0);
                            map2.put("failreason", errmsg);
                            rabbitMQSender.send(RabbitMqQueueNameConstant.PAYORDER_CALLBACK, JSON.toJSONString(map2));
                        }
                        break;
                }
            }else {
                if (resultJson.getStatus() == -2){
                    logger.debug(resultJson.getMsg());
                    return;
                }else {
                    rabbitMQSender.send(RabbitMqQueueNameConstant.DEAD_PAYORDER_QUERY_10MIN, tradenum);
                    jedis.incr(RedisKeyConstant.PAYORDER_QUERY_TIMES + tradenum);
                }
            }
        }catch (Exception e){
            logger.error(tradenum+"订单查询队列处理异常",e);
        }finally {
            redisDao.close(jedis);
        }
    }
}
